<template>
  <view class="container">
    <!-- Header with search and add button -->
    <view class="header">
      <uni-search-bar v-model="searchTerm" @confirm="fetchStores" placeholder="搜索门店" class="search-bar"></uni-search-bar>
      <uni-button type="primary" size="mini" @click="openAddPopup">新增门店</uni-button>
    </view>

    <!-- Store list table -->
    <uni-table :border="true">
      <uni-tr>
        <uni-th align="center">门店名称</uni-th>
        <uni-th align="center">联系电话</uni-th>
        <uni-th align="center">地址</uni-th>
        <uni-th align="center">联系人</uni-th>


        <uni-th align="center">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="store in filteredStores" :key="store.id">
        <uni-td align="center">{{ store.name }}</uni-td>
        <uni-td align="center">{{ store.phone }}</uni-td>
        <uni-td align="center">{{ store.address }}</uni-td>
        <uni-td align="center">{{ store.contact }}</uni-td>

        <uni-td align="center">
          <uni-button type="default" size="mini" @click="openEditPopup(store)">编辑</uni-button>
          <uni-button type="error" size="mini" @click="openDeletePopup(store)">删除</uni-button>
        </uni-td>
      </uni-tr>
    </uni-table>

    <!-- Popup for adding/editing a store -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-container">
        <h3>{{ currentStore.id ? '编辑门店' : '新增门店' }}</h3>
        <view class="form-row">
          <label>门店名称：</label>
          <input v-model="currentStore.name" class="input-field" />
          <label>联系人：</label>
          <input v-model="currentStore.contact" class="input-field" />
        </view>
        <view class="form-row">
          <label>联系电话：</label>
          <input v-model="currentStore.phone" class="input-field" />
          <label>门店地址：</label>
          <input v-model="currentStore.address" class="input-field" />
          <!-- <uni-button type="primary" size="mini" class="location-button">定位</uni-button> -->
        </view>
        <!-- <view class="form-row">
          <label>营业执照：</label>
          <input v-model="currentStore.license" class="input-field" />
          <label>云打印机：</label>
          <input v-model="currentStore.printer" class="input-field" />
          <uni-button type="default" size="mini" class="device-management">设备管理</uni-button>
        </view>
        <view class="form-row">
          <label>本机收款语音提醒：</label>
          <input v-model="currentStore.voice_reminder" class="input-field" />
        </view> -->
        <!-- <view class="form-row full-width">
          <label>门店介绍：</label>
          <view class="editor-container">
            <Editor v-model="currentStore.description" />
          </view>
        </view>
        <view class="form-row full-width">
          <label>上传图片：</label>
          <view class="upload-box" @click="uploadImage">
            <view v-if="currentStore.image">
              <image :src="currentStore.image" class="preview-image" />
            </view>
            <view v-else>
              <text>点击上传图片</text>
              <text>上传尺寸：640*640</text>
            </view>
          </view>
        </view> -->
        <view class="button-group">
          <uni-button type="primary" size="small" @click="saveStore">保存</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>

    <!-- Popup for confirming deletion -->
    <uni-popup ref="deletePopup" type="center">
      <view class="popup-container">
        <h3>确认删除</h3>
        <text>确定要删除 "{{ currentStore.name }}" 吗？</text>
        <view class="button-group">
          <uni-button type="error" size="small" @click="confirmDelete">删除</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import Editor from '@/components/Editor/Editor.vue'; 

export default {
  components: {
    Editor
  },
  data() {
    return {
      searchTerm: '',
      stores: [],
      filteredStores: [],
      currentStore: {},
      userId: 1 // Replace with the actual user ID
    };
  },
  methods: {
    async fetchStores() {
      const res = await this.$myRuquest({
        url: `/index/plugin.users/getStores?user_id=${this.userId}&searchTerm=${this.searchTerm}`,
        method: 'GET'
      });
      if (res.data.code === 200) {
        this.stores = res.data.data;
		console.log(res.data.data);
        this.filterStores();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    filterStores() {
      if (this.searchTerm) {
        this.filteredStores = this.stores.filter(store => 
          store.name.includes(this.searchTerm) ||
          store.contact.includes(this.searchTerm) ||
          store.address.includes(this.searchTerm)
        );
      } else {
        this.filteredStores = this.stores;
      }
    },
    openAddPopup() {
      this.currentStore = { id: null, user_id: this.userId, name: '', phone: '', address: '', contact: '', type: '', license: '', printer: '', voice_reminder: '', description: '', image: '' };
      this.$refs.editPopup.open();
    },
    openEditPopup(store) {
      this.currentStore = Object.assign({}, store);
      this.$refs.editPopup.open();
    },
    closePopup() {
      this.$refs.editPopup.close();
      this.$refs.deletePopup.close();
    },
    async saveStore() {
      const method = this.currentStore.id ? 'PUT' : 'POST';
      const res = await this.$myRuquest({
        url: '/index/plugin.users/saveStore',
        method: method,
        data: this.currentStore
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchStores();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.info,
          icon: 'none',
          duration: 2000
        });
      }
    },
    openDeletePopup(store) {
      this.currentStore = Object.assign({}, store);
      this.$refs.deletePopup.open();
    },
    async confirmDelete() {
      const res = await this.$myRuquest({
        url: '/index/plugin.users/deleteStore',
        method: 'DELETE',
        data: { id: this.currentStore.id }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchStores();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.info,
          icon: 'none',
          duration: 2000
        });
      }
    },
	//检查是否登录
	checkLoginStatus() {
	  const token = uni.getStorageSync('token');
	  if (token) {
	    this.isLoggedIn = true;
	    this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
	    this.fetchMenus();
	  } else {
	    this.isLoggedIn = false;
	    this.userInfo = {};
	    this.$router.push('/pages/login/login');
	  }
	},
    uploadImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.currentStore.image = tempFilePath;
        }
      });
    }
  },
  mounted() {
    this.fetchStores();
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}

.search-bar {
  flex: 1;
  max-width: 50%;
  margin: 0 10px;
}

.main-content {
  text-align: center;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h3 {
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
}

label {
  width: 100px; /* 增加标签宽度，确保对齐 */
  color: #666;
  margin-right: 10px;
  text-align: right; /* 确保标签文字右对齐 */
}

.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.popup-container {
  width: 80%;
  max-width: 800px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
}

.form-row.full-width {
  flex-direction: column;
  width: 100%;
}

.upload-box {
  width: 100%;
  border: 1px dashed #ddd;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}

.preview-image {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

.location-button,
.device-management {
  margin-left: 10px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  width: 100%;
}

/* 富文本编辑器的样式 */
.editor-container {
  width: 100%; /* 确保编辑器容器占据整个宽度 */
  height: 300px; /* 调整高度使其适应屏幕 */
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fff;
  margin-top: 10px;
}

.editor-container .ql-container {
  height: 100%; /* 确保编辑器填满容器 */
}
</style>
